import React, { Component } from 'react'
import './index.css';
import axios from 'axios';
export default class App extends Component {

    state = {
        duanzi: [

        ],
        author: '',
        content: ''
    }

    render() {
        return <div>
            {/* 左侧的表单区域 start */}
            <div className="left">
                作者<br /><input  onChange={this.saveData('author')} type="text"  value={this.state.author} /><br />
                内容<br /> <textarea  onChange={this.saveData('content')} value={this.state.content} cols="30" rows="10"></textarea><br />
                <button onClick={this.addDuanzi}>新增</button>
            </div>
            {/* 左侧的表单区域 end */}

            {/* 右侧的列表区域 start */}
            <div className="right">
                <h2>段子列表</h2>
                <table border="1">
                    <thead>
                        <tr><td>ID</td><td>作者</td><td>段子内容</td><td width="80">操作</td></tr>
                    </thead>

                    <tbody>
                        {
                            this.state.duanzi.map(item => {
                                return <tr key={item.id}>
                                    <td>{item.id}</td>
                                    <td>{item.name}</td><td>{item.text}</td>
                                    <td><button did={item.id} onClick={this.removeDuanzi}>点击删除</button></td></tr>
                            })
                        }
                    </tbody>
                </table>
            </div>
            {/* 右侧的列表区域 end */}

        </div>
    }

    addDuanzi = async () => {
        //获取数据
        let obj = {
            name: this.state.author,
            text: this.state.content
        }
        //发送请求
        let result = await axios.post('http://127.0.0.1:3002/duanzi', obj);
        //判断
        if(result.status === 201){
            alert('新增成功');
            //更新页面的内容
            this.setState({
                duanzi: [...this.state.duanzi, result.data]
            })
        }else{
            alert('新增失败');
        }
    }


    //保存表单数据
    saveData(type){
        return (e) => {
            this.setState({
                [type]: e.target.value
            })
        }
    }

    removeDuanzi = async (e) => {
        if (!window.confirm('您确定要删除该段子么')) return;
        // 删除服务端的那一条段子  restful API     GET 获取 POST 新增  PATCH  PUT  更新  DELETE 删除数据
        //获取对应的 id
        let id = e.target.getAttribute('did');
        let result = await axios({
            method: 'delete',
            url: 'http://127.0.0.1:3002/duanzi/' + id
        });
        //更新页面的显示
        this.setState({
            duanzi: this.state.duanzi.filter(item => item.id !== Number(id))
        })
    }

    async componentDidMount() {
        //发送 AJAX 请求
        let { data } = await axios.get('http://127.0.0.1:3002/duanzi')
        //设置 state 中段子属性的值
        this.setState({
            duanzi: data
        })
    }
}
